package ooo.reindeer.commons.concurrent;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

public class NamedThreadFactory implements ThreadFactory {

    static AtomicLong poolSerialNumber = new AtomicLong(1);
    final String name;
    AtomicLong serialNumber = new AtomicLong(1);

    public NamedThreadFactory(String name) {
        this.name = name;
    }

    String getThreadName(String name) {
        if (name == null || name.isEmpty()) {
            return "pool-" + poolSerialNumber.getAndIncrement() + "-worker-" + serialNumber.getAndIncrement();
        } else {
            return "pool-" + name + "-worker-" + serialNumber.getAndIncrement();
        }
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setName(getThreadName(name));
        return thread;
    }
}
